from urllib import request,parse
import json

def fanyi(keyword):
    base_url = 'http://fanyi.baidu.com/sug'

    # 构建请求对象
    data = {
        'kw' : keyword
    }
    data = parse.urlencode(data)

    headers = {
        'Content-Length':len(data)
    }

    req = request.Request(url=base_url,data=bytes(data,encoding='utf-8'),headers=headers)
    res = request.urlopen(req)

    str_json = res.read().decode('utf-8') # 获取响应的json字串
    myjson = json.loads(str_json) # 把json转字典
    info = myjson['data'][0]['v']
    print(info)

if __name__ == '__main__':
    while True:
        keyword = input('输入翻译的单词：')
        if keyword == 'q':
            break
        fanyi(keyword)